
#include "ctrl_bsp_btn.h"
#include "oslib.h"
// ----------------------------------------------
/* 按钮信息 */
typedef struct {
	bool Pressed;
	bool PinReverse;
	uint16_t GPIO_Pin;
	GPIO_TypeDef* GPIO_Port;
} Button_TypeDef_t;

// ----------------------------------------------
/* 按钮按下/释放对应的GPIO引脚状态 */
#define GPIO_BTN_PRESSED GPIO_PIN_RESET
#define GPIO_BTN_RELEASED GPIO_PIN_SET

/* 按钮数量 */
#define BTN_MAX_COUNT 16
#define BTN_COUNT 10

// ----------------------------------------------
/* 按钮列表 */
static Button_TypeDef_t btn_list[BTN_COUNT] = {
	{0,	0, 	Button_1_Pin,		Button_1_GPIO_Port	  },
	{0,	0, 	Button_2_Pin, 		Button_2_GPIO_Port	  },
	{0,	0, 	Button_3_Pin, 		Button_3_GPIO_Port	  },
	{0,	0, 	Button_4_Pin, 		Button_4_GPIO_Port	  },
	{0,	0, 	Button_5_Pin, 		Button_5_GPIO_Port	  },
	{0,	0, 	Button_6_Pin, 		Button_6_GPIO_Port    },
	{0,	0, 	Button_7_Pin, 		Button_7_GPIO_Port	  },
	{0,	0, 	Button_8_Pin, 		Button_8_GPIO_Port	  },
	{0,	0, 	Button_Left_Pin, 	Button_Left_GPIO_Port },
	{0,	0, 	Button_Right_Pin,	Button_Right_GPIO_Port},
};

// ----------------------------------------------

/**
 * @brief 扫描物理按键, 得到各按键按下情况
 * 
 * @return uint16_t 16位依次表示各按键是否按下
 */
Button_Value_t Button_KeyScan()
{
	uint8_t index;
	uint16_t press_state = 0;

	for (index = 0; index < BTN_COUNT; index++)
	{
		if (HAL_GPIO_ReadPin(btn_list[index].GPIO_Port, btn_list[index].GPIO_Pin) 
			== (!btn_list[index].PinReverse ? GPIO_BTN_PRESSED : GPIO_BTN_RELEASED))
			press_state |= (1UL << index);
		else
			press_state &= ~(1UL << index);
	}

	return press_state;
}

/**
 * @brief 获取拨码开关的值
 * 
 * @return uint8_t 高4位为0, 低4位对应拨码开关的值
 */
uint8_t Switch_GetState()
{
	uint8_t state = 0;
	if (HAL_GPIO_ReadPin(Switch_3_GPIO_Port, Switch_3_Pin))
		state |= (1<<3);
	if (HAL_GPIO_ReadPin(Switch_2_GPIO_Port, Switch_2_Pin))
		state |= (1<<2);
	if (HAL_GPIO_ReadPin(Switch_1_GPIO_Port, Switch_1_Pin))
		state |= (1<<1);
	if (HAL_GPIO_ReadPin(Switch_0_GPIO_Port, Switch_0_Pin))
		state |= (1<<0);
	return state;
}